#从集思录获取最近发行的可转债信息
# -*- coding:utf-8 -*-
import json
import sys

import requests
import csv
import re
from lxml import etree
import os,subprocess,time,schedule,datetime
import pandas as pd

def send_wechat_msg(content):
    webhook_url= "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a09b6499-562d-4101-a0bb-6af13b54fb97"
    data = {"msgtype": "text", 
    "mentioned_list":["张文强"],
    "text": {"content": content}}
    proxies = {
        "http": None,
        "https": None,
    }
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.40 Safari/537.36 Edg/87.0.664.24'
    }
    requests.packages.urllib3.disable_warnings()
    r = requests.post(url=webhook_url,headers=header, data=json.dumps(data, ensure_ascii=False).encode('utf-8'), verify=False,proxies=proxies)
    return r.text, r.status_code

def get_data():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
    }

    newUrl ="https://www.jisilu.cn/data/cbnew/pre_list/?___jsl=LST___t=1584777951900"
    #最简单的爬虫请求.也可以加上headers字段，防止部分网址的反爬虫机制
    response = requests.get(newUrl)
    #当爬取的界面需要用户名密码登录时候，构建的请求需要包含auth字段
    data = response.content.decode("utf-8")
    dat = json.loads(data)
    #print(dat['rows'][0])
    # 所有数据
    lst_data = []
    for one in dat['rows']:
        # 每一条数据
        lst_dat = []
        # 转债id
        id = one["id"]
        dat_cell = one["cell"]
        # 是否赎回
        is_shui =  dat_cell['apply_date']
        if is_shui != None:
            #上市转债代码
            Bid = dat_cell['bond_id']
            # 转债名称
            name = dat_cell['bond_nm']
            # 申购日期
            apply_date = dat_cell['apply_date']
            # 申购代码
            apply_cd = dat_cell['apply_cd']
            # 上市日期
            list_date = dat_cell['list_date']

            lst_dat.append(id)
            lst_dat.append(Bid)
            lst_dat.append(name)
            lst_dat.append(apply_date)
            lst_dat.append(list_date)
            lst_data.append(lst_dat)
        else:
            continue

    for bond in  lst_data:
        today = datetime.date.today()
        tomorrow = str(today + datetime.timedelta(days=1))
        # 判断是否明天是否有申购的新债
        if bond[3]==tomorrow:
            send_wechat_msg(f"【新债申购】明天有可申购的新债:{bond[2]}")
        # 判断是否明天是否有上市的新债
        elif bond[4]==tomorrow:
            dealBondPath=os.join(sys.path[0],dealBond.csv)
            dealBond=pd.read_csv(dealBondPath)
            print(dealBond)
            dealList=dealBond["中签代码"].tolist()
            if int(bond[1]) in dealList:
                accountDeal=dealBond[dealBond["中签代码"]==int(bond[1])]["中签人"].tolist()
                send_wechat_msg(f"【新债上市】明天有可上市的中签新债:{bond[2]}，中签人：{accountDeal}")
                





schedule.every().day.at("21:30").do(get_data)
while True:
    schedule.run_pending()
    time.sleep(1800)



